<template>
  <div class="todo">
    <AddInput :addTodo="addTodo" />
    <TodoList
      :todos="todos"
      :toggleTodo="toggleTodo"
      :deleteTodo="deleteTodo"
    />
    <TodoFooter
      :todos="todos"
      :onAllSelectChange="onAllSelectChange"
      :onClear="onClear"
    />
  </div>
</template>

<script>
import AddInput from "./AddInput.vue";
import TodoList from "./TodoList.vue";
import TodoFooter from "./TodoFooter.vue";

export default {
  name: "Todo",
  components: {
    AddInput,
    TodoList,
    TodoFooter,
  },
  data() {
    return {
      todos: [],
    };
  },
  methods: {
    addTodo(name) {
      const todo = {
        name: name,
        id: Math.random().toString(36).substring(6),
        done: false,
      };
      this.todos.unshift(todo);
    },
    toggleTodo(id) {
      const index = this.todos.findIndex((todo) => todo.id === id);
      this.todos[index].done = !this.todos[index].done;
    },
    deleteTodo(id) {
      const index = this.todos.findIndex((todo) => todo.id === id);
      this.todos.splice(index, 1);
    },
    onAllSelectChange(allSelect) {
      console.log("allSelect", allSelect);

      this.todos = this.todos.map((todo) => {
        todo.done = allSelect;
        return todo;
      });
    },
    onClear() {
      if (confirm("确认要清除所有吗?")) {
        this.todos = [];
      }
    },
  },
};
</script>

<style scoped>
.todo {
  width: 300px;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
</style>
